<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    top="5vh"
    width="80%"
    max-height="70vh"
    :scroll="true"
    :close-on-press-escape="false"
  >
    <template v-if="reviewApplyInfo">
      <div class="mb-16px">
        <div class="title">{{ t('reviewApplyInfo.baseInfo.title') }}</div>
        <BaseInfo ref="baseInfoRef" :data="reviewApplyInfo.baseInfo" :disabled="editDisabled" />
      </div>
      <div class="mb-16px">
        <div class="title">{{ t('reviewApplyInfo.projectList.title') }}</div>
        <ProjectTable
          ref="projectTableRef"
          :list="reviewApplyInfo.projectList"
          :disabled="editDisabled"
        />
      </div>
      <div class="mb-16px">
        <div class="title">{{ t('reviewApplyInfo.highLevelPaperList.title') }}</div>
        <HighLevelPaperTable
          ref="highLevelPaperTableRef"
          :list="reviewApplyInfo.highLevelPaperList"
          :disabled="editDisabled"
        />
      </div>
      <div class="mb-16px">
        <div class="title">{{ t('reviewApplyInfo.monographList.title') }}</div>
        <MonographTable
          ref="monographTableRef"
          :list="reviewApplyInfo.monographList"
          :disabled="editDisabled"
        />
      </div>
      <div class="mb-16px">
        <div class="title">{{ t('reviewApplyInfo.patentList.title') }}</div>
        <PatentTable
          ref="patentTableRef"
          :list="reviewApplyInfo.patentList"
          :disabled="editDisabled"
        />
      </div>
      <div class="mb-16px">
        <div class="title">{{ t('reviewApplyInfo.awardList.title') }}</div>
        <AwardTable
          ref="awardTableRef"
          :list="reviewApplyInfo.awardList"
          :disabled="editDisabled"
        />
      </div>
    </template>
    <template #footer>
      <el-button v-if="isEdit" @click="handleConfirm" type="primary" :disabled="formLoading">{{
        t('common.ok')
      }}</el-button>
      <el-button v-if="isEdit" @click="dialogVisible = false">{{
        isEdit ? t('common.cancel') : t('common.close')
      }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { ReviewApplyApi, ReviewApplyVO } from '@/api/recruit/reviewApply'
import { BaseInfoVO, ReviewApplyInfoDto, ReviewApplyInfoVO } from '@/api/recruit/reviewApply/types'
import {
  BaseInfo,
  ProjectTable,
  HighLevelPaperTable,
  MonographTable,
  PatentTable,
  AwardTable
} from '@/views/recruit/components/qualificationReview'
import { cloneDeep } from 'lodash-es'

/** 导师遴选申请/申请信息 */
defineOptions({ name: 'ReviewApplyDialog' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const baseInfoRef = ref<InstanceType<typeof BaseInfo>>()
const projectTableRef = ref<InstanceType<typeof ProjectTable>>()
const highLevelPaperTableRef = ref<InstanceType<typeof HighLevelPaperTable>>()
const monographTableRef = ref<InstanceType<typeof MonographTable>>()
const patentTableRef = ref<InstanceType<typeof PatentTable>>()
const awardTableRef = ref<InstanceType<typeof AwardTable>>()

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const isEdit = ref(false) // 是否是编辑状态
const batchId = ref('') // 批次id
const reviewApplyInfo = ref<ReviewApplyInfoVO>() // 申请信息
// 基本信息
const userBaseInfo: BaseInfoVO = {
  realName: '',
  gender: '1',
  birthday: '',
  researchGroup: '',
  workTel: '',
  email: '',
  phone: '',
  technicalPosition: '',
  enrollmentMajor: '',
  highestDegree: '',
  mainAcademic: '',
  researchDirection: ''
}

// 编辑禁用状态
const editDisabled = computed(() => !isEdit.value || formLoading.value)

// 解析申请信息
const parseApplyInfo = (applyData: ReviewApplyInfoDto) => {
  // console.log('parseApplyInfo -> applyData', applyData)
  const parseJSON = (data: string, defaultValue: any) => {
    try {
      return JSON.parse(data)
    } catch {
      return defaultValue
    }
  }
  // 申请信息为空时，设置默认值
  if (!applyData) {
    resetData()
    return
  }
  // 申请信息为空对象时，设置为空字符串 使后面解json时走异常处理条件
  if (applyData.baseInformation === '{}') {
    applyData.baseInformation = ''
  }
  reviewApplyInfo.value = {
    baseInfo: parseJSON(applyData.baseInformation, cloneDeep(userBaseInfo)),
    projectList: parseJSON(applyData.projects, []),
    highLevelPaperList: parseJSON(applyData.paper, []),
    monographList: parseJSON(applyData.monograph, []),
    patentList: parseJSON(applyData.patent, []),
    awardList: parseJSON(applyData.award, [])
  }
}

// 处理申请信息为提交数据结构
const handleApplyInfo = () => {
  const baseInfo = baseInfoRef.value?.formData ?? {}
  const projectList = projectTableRef.value?.getTableData() ?? []
  const highLevelPaperList = highLevelPaperTableRef.value?.getTableData() ?? []
  const monographList = monographTableRef.value?.getTableData() ?? []
  const patentList = patentTableRef.value?.getTableData() ?? []
  const awardList = awardTableRef.value?.getTableData() ?? []

  return {
    baseInformation: JSON.stringify(baseInfo),
    projects: JSON.stringify(projectList),
    paper: JSON.stringify(highLevelPaperList),
    monograph: JSON.stringify(monographList),
    patent: JSON.stringify(patentList),
    award: JSON.stringify(awardList)
  }
}

// 获取申请信息
const getApplyInfo = async () => {
  if (!batchId.value) {
    return
  }
  formLoading.value = true
  try {
    const data = await ReviewApplyApi.getApplyInfo(batchId.value)
    if (data.list?.length) {
      parseApplyInfo(data.list[0])
    }
  } catch {}
  formLoading.value = false
}

/** 打开弹窗 */
const open = async (edit: boolean, row: ReviewApplyVO) => {
  dialogVisible.value = true
  dialogTitle.value = edit
    ? t('reviewApply.applyDialog.title.apply')
    : t('reviewApply.applyDialog.title.view')
  isEdit.value = edit
  resetData()
  batchId.value = row.id
  // 查看时，设置数据
  if (!edit) {
    await getApplyInfo()
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const handleConfirm = async () => {
  try {
    // 提示
    await ElMessageBox.confirm(t('reviewApply.applyDialog.tips'), t('common.confirmTitle'), {
      confirmButtonText: t('reviewApply.applyDialog.confirmButton'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    })
    // 提交请求
    formLoading.value = true
    const dataAfterHandle = handleApplyInfo()
    // console.log('handleConfirm -> dataAfterHandle', { batchId: batchId.value, ...dataAfterHandle })
    await ReviewApplyApi.apply({ batchId: batchId.value, ...dataAfterHandle })
    message.success(t('reviewApply.applyDialog.submitSuccess'))
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const resetData = () => {
  reviewApplyInfo.value = {
    baseInfo: cloneDeep(userBaseInfo),
    projectList: [],
    highLevelPaperList: [],
    monographList: [],
    patentList: [],
    awardList: []
  }
}

const initData = async () => {
  try {
    // 查询导师信息
    const data = await ReviewApplyApi.getCurrentMentorInfo()
    userBaseInfo.realName = data?.nickname ?? ''
    userBaseInfo.gender = data?.xbm === '女性' ? '2' : '1'
    userBaseInfo.birthday =
      data?.csrq && data.csrq.length === 8
        ? `${data.csrq.slice(0, 4)}-${data.csrq.slice(4, 6)}-${data.csrq.slice(6, 8)}`
        : ''
    userBaseInfo.workTel = data?.dwdh ?? ''
    userBaseInfo.email = data?.email ?? ''
    userBaseInfo.phone = data?.yddh ?? ''
    userBaseInfo.technicalPosition = data?.xzzw ?? ''
    userBaseInfo.mainAcademic = data?.zyshxwttjz ?? ''
    userBaseInfo.researchDirection = data?.zyyjfx ?? ''
    // console.log('initData -> userBaseInfo', userBaseInfo)
  } catch {}
}

onMounted(() => {
  initData()
})
</script>
<style scoped lang="scss">
.title {
  margin-bottom: 8px;
  font-size: 14px;
  height: 24px;
  line-height: 24px;
  font-weight: bold;

  &::before {
    content: '';
    display: inline-block;
    width: 4px;
    height: 12px;
    line-height: 24px;
    background-color: var(--el-color-primary);
    margin-right: 5px;
  }
}
</style>
